/*** Class Name: IfulfillQueryEmailHandler 
 * Author: Accenture
 * Date: 13-Sep-2011
 * Requirement/Project Name: iFulfill
 * Requirement Description: Handles incoming email Query
 **/
 
global class IfulfillQueryEmailHandler implements Messaging.InboundEmailHandler 
{
   /*
    *  Handles the inbound e-mail.
    *
    **/
  global Messaging.InboundEmailResult handleInboundEmail(Messaging.InboundEmail email, Messaging.InboundEnvelope env) 
  {
         System.debug (' Enter the class IfulfillQueryEmailHandler handleInboundEmail method');
         
         Messaging.InboundEmailResult result = new Messaging.InboundEmailresult(); 
         String txt =email.subject;
         String queryName = null;
         Integer startIndex = null;
         Integer endIndex = null;
         boolean found = true; 
         Pattern emailPattern = Pattern.compile(IfullfillTextConstant.QUERY_NAME_PATTERN);
         Matcher emailMatcher = emailPattern.matcher(txt);

         // Searching the Subject  for Query name Pattern 
         if( txt!= null && emailMatcher.find())
         {
             found = false;
             startIndex = emailMatcher.start();
             endIndex = emailMatcher.end();
             queryName =txt.substring(startIndex,endIndex );
             insertTask(queryName,email);
         }
         else
         {
            // Searching the mail message  for Query  name Pattern 
             txt = email.plainTextBody;
             emailMatcher = emailPattern.matcher(txt);
             if( txt!= null && emailMatcher.find())
             {
                found = false;
                startIndex = emailMatcher.start();
                endIndex = emailMatcher.end();
                queryName =txt.substring(startIndex,endIndex );
                insertTask(queryName,email);
             }              
         }
          if(found)
         {
                 System.debug('Query name Pattern not found ');
         }        
         return result;
    }
         /*
          * Insert the Task if the Query name match is found.
          *
          **/
         public void insertTask(String queryName , Messaging.InboundEmail email )
         {
             String emailHeader  = '';
             String address = '';
             List <Task> taskList = new List<Task>();
             List <Attachment> attachmentList ;
             Task newTask;
             List<Queries__c>  queryList =[select id, ownerid  from Queries__c  where Name = :queryName.trim() ];                     
             RecordTypeIDs__c listViewIDObj = RecordTypeIDs__c.getInstance(userinfo.getProfileId());
            
             address  = email.fromName != null ?  email.fromName : '';
             emailHeader  = 'From :' + address  + ' ' + email.fromAddress +'\n';
             address  = ''; 
              if(email.toAddresses !=null  )
              {   
                 for(String str  : email.toAddresses ) 
                 {
                         address  = address  + str + ';'; 
                 }
             }
             emailHeader   = emailHeader  + 'To : ' + address  + '\n';
             address  = ''; 
             System.debug('cc adddress'+email.ccAddresses+'toaddress'+email.toAddresses);
             if(email.ccAddresses!=null  )
              {   
                 for(String str  : email.ccAddresses) 
                 {
                         address  = address  + str + ';'; 
                 }
             }
             emailHeader   = emailHeader  + 'Cc : ' + address  + '\n';
             address  = '';
             address  = email.subject != null ?   email.subject  : '';
             emailHeader  = emailHeader  + 'Subject : ' +address ;

             if(queryList.size() > 0 )
             {
                 String ownerID = queryList.get(0).ownerid;
                   newTask = new Task(
                                      RecordTypeID = listViewIDObj.IFulfillTaskRecordType__c,
                                      Description = emailHeader +'\n \n' +email.plainTextBody ,
                                      Priority = 'Normal',
                                      Subject = email.subject,
                                      ReminderDateTime = System.now(),
                                      WhatId = queryList.get(0).id);   
                                      
                 // Check the Query object  owner is queue or  user                  
                 if(ownerID.startsWith(IfullfillTextConstant.USER_ID_STARTS_WITH))
                 {
                     newTask.OwnerID = ownerID;                         
                 }
                 else
                 {
                     // Query owner is Queue
                     System.debug('Query Owner is a Queue');  
                 }     
                 taskList.add(newTask);           
            }
            else
            {
                 System.debug('invalid Query name ' + queryName);
            }                  
            try
            {
                if(taskList.size()> 0)
                {
                    insert taskList ;
                    attachmentList = processEmailAttachment(email,taskList);
                    if(attachmentList !=null && attachmentList.size() > 0 )
                    {
                        insert attachmentList;
                    }
                }
            }
            catch(DmlException e1)
            {
                 GeneralConstants.mailAnyExceptionToMe('IfulfillQueryEmailHandler ','insertTask',e1);
            }
            catch(Exception e)
            {
                 GeneralConstants.mailAnyExceptionToMe('IfulfillQueryEmailHandler ','insertTask',e);
                 System.debug('Task insertion failed '+ e );
            }        
     }
   /*
    * Process any attchment if peresent in  inbound email.
    *
    **/ 
    
    private List<Attachment> processEmailAttachment( Messaging.InboundEmail email, List<Task> taskList)
    {
        List <Attachment> attachmentList = new List<Attachment>();
        List <Task> tempTaskList = [Select id,ownerID  from Task where id = : taskList.get(0).id]; 
        if(tempTaskList.size() > 0)
        {
             // Check if we have any text attachment                       
             if (email.textAttachments!= null && email.textAttachments.size() > 0) 
             {
                 System.debug ('Receviced mail with text  attachment');
                 for (Messaging.Inboundemail.TextAttachment tAttachment : email.textAttachments) 
                 {
                     Attachment attachment = new Attachment();
                     attachment.Name = tAttachment.fileName;
                     attachment.Body = Blob.valueOf(tAttachment.body);
                    attachment.ParentId = tempTaskList.get(0).id;
                     attachment.ownerId = tempTaskList.get(0).ownerid;
                     attachmentList.add(attachment); 
                 }
             }
             // Check if any binary attachment are present.       
             if (email.binaryAttachments != null && email.binaryAttachments.size() > 0) 
             {
                   System.debug ('Receviced mail with binary attachment'); 
                   
                   for (integer i = 0 ; i < email.binaryAttachments.size() ; i++) 
                   {
                       Attachment attachment = new Attachment();
                       // attach to the newly created contact record
                       attachment.ParentId = tempTaskList.get(0).id;
                       attachment.ownerId = tempTaskList.get(0).ownerid;
                       attachment.Name = email.binaryAttachments[i].filename;
                       attachment.Body = email.binaryAttachments[i].body;
                       attachmentList.add(attachment); 
                   }     
              }        
         }
         return attachmentList;
     }                       
}